<template>
  <div class="flex justify-center index overauto"
       style="width: 100vw;height: 100vh;overflow-x: hidden;">
    <div class="content" v-if="!showSuccess && !showOrder">
      <div
        class="top-title text-[18px] text-[#fff] bg-[#FD4442] w-[100%] flex items-center px-[10PX] items-center py-[18PX] relative pl-[40px] relative">
        <div class="py-[18PX] h-[100%] absolute top-[0px] left-[18px] bar">
          <div class=" h-[100%] bg-[#FF8800] mr-[5px] ">

          </div>
        </div>

        {{ product.titleExternal }}
      </div>

      <div class="relative swiper">
        <el-carousel :autoplay="true" :interval="5000">
          <el-carousel-item v-for="(item,index) in product.picture?.split(',')"
                            :key="index"
          >
            <div class="swiper-item bg"
                 :style="`background-image: url(${ item })`">

            </div>
          </el-carousel-item>
        </el-carousel>

        <SwiperBuyInfo :list="rollList" :product="product" v-if="rollList?.style=='1'"/>


        <div class="w-[100%]  benefit bg flex items-center px-[10PX] justify-between "
             v-if="product.countdown"
             style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN01JgZMVC2IpwkOVkeDq_!!801089336.png);background-position: right top;">
          <div style="gap:10px" class="flex text-[#fff] items-center text-[12PX]">
            <div class="text-[#fff] ">{{ language.limitTime }}</div>
            |
            <div class="qianggou-num bg-[#fff] rounded-[24PX] text-[#FD4442]  text-[12PX]">
              {{ language.salesNum }}：{{ product.saleCount || 0 }}
            </div>
          </div>

          <div style="gap: 5px" class="flex items-center time">
            <div class="text-[#FD4442]  text-[12PX]">{{ language.distanceEnd }}：</div>

            <div class="cycle flex-center text-[#fff]  text-[12PX]">
              {{ time.hours }}
            </div>

            <div class=" text-[#FD4442]  text-[12PX]">
              :
            </div>

            <div class="cycle  flex-center text-[#fff]  text-[12PX]">
              {{ time.minutes }}
            </div>

            <div class=" text-[#FD4442]  text-[12PX]">
              :
            </div>

            <div class="cycle  flex-center text-[#fff]  text-[12PX]">
              {{ time.seconds }}
            </div>

          </div>

        </div>


        <div class="px-[10PX] py-[18PX] flex items-end ">
          <div class=" text-[#FF0C06] mr-[10px] flex items-end">
            <div class="symbol text-[#FF0C06]">{{ areaInfo.currencySymbol }}</div>
            <div class="price text-[#FF0C06] text-bold">
              {{ product.discountedPrice || product.originalPrice || 0 }}
            </div>
          </div>
          <div class="text-[#C7C7C7]" v-if=" product.discountedPrice">
            {{ language.originPrice }}：{{ areaInfo.currencySymbol }}{{ product.originalPrice || 0 }}
          </div>
        </div>


        <div class="coupon bg mt-[15PX] flex items-center justify-between px-[10PX]"
             v-if="product.couponAmount"
             style="background-image: url(https://img.alicdn.com/imgextra/i3/801089336/O1CN018OYOCV2IpwkNUBJ3S_!!801089336.png);background-position: top left;">
          <div>
            无门槛优惠券·预计省下 <span class="text-[#FF0C06]">{{
              areaInfo.currencySymbol
            }}{{ product.couponAmount }}</span>
          </div>

          <div class="px-[12PX] py-[6PX] rounded-[60PX] text-[#FDB03A]"
               style="border: solid 1px #FDB03A" @click="handleBtnClick({ type:'pickupCoupon' })">
            {{ isPickup ? '已领取' : '立即领取' }}
          </div>

        </div>

        <div class="top-title mt-[15PX] px-[10PX]">
          {{ product.titleExternal }}
        </div>

        <div class="subTitle text-[#999999] mt-[15PX] px-[10PX]">
          {{ product.subtitle }}
        </div>

        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="mt-[15PX] px-[10PX] flex" v-if=" productInfo.tagValue">
          <div class="flex mr-[20PX] items-center"
               v-for="(item,index) in productInfo.tagValue?.split(',')"
               :key="index"

          >
            <div class="icons bg"

                 style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN017XkvI42IpwkOf9NSw_!!801089336.png)">

            </div>

            <div class="ml-[5PX]">
              {{ item }}
            </div>
          </div>
        </div>

        <div class="gap w-[100%] h-[10PX] bg-[#F5F5F5] my-[15PX]">

        </div>


        <div class="detailPart">
          <div
            class="top-title text-[18px] text-[] bg-[] w-[100%] flex items-center px-[10PX] items-center py-[18px] relative pl-[30PX] relative">
            <div class="py-[18px] h-[100%] absolute top-[0px] left-[18px]">
              <div class="w-[4PX] h-[100%] bg-[#FF8800] mr-[5px] ">

              </div>
            </div>

            {{ language.productDetail }}
          </div>

          <div class="py-[15PX] htmlDetails" v-html="product.detail">

          </div>


          <div class="mt-[15PX]">
            <Recommend :recommend-list="recommendList"
                       v-if="recommendList && recommendList.length>0"/>
          </div>


        </div>


        <div>
          <div class="mt-[6PX] px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]">
            <div class="empty" v-if="!commentList || commentList.length == 0">
              {{ language.noComment }}
            </div>
            <!-- 有評價時引入評價組件 -->

            <Evaluation v-else :comment-list="commentList" :comment-avg-score="commentAvgScore"
                        :product="product"/>
          </div>

        </div>


        <div class="gap w-[100%] h-[10PX] bg-[#F5F5F5] my-[15PX]">

        </div>

        <div class="detailPart">


          <div
            class="top-title text-[18px] text-[] bg-[] w-[100%] flex items-center px-[10PX] items-center py-[18px] relative pl-[30PX] relative">
            <div class="py-[18px] h-[100%] absolute top-[0px] left-[18px]">
              <div class="w-[4PX] h-[100%] bg-[#FF8800] mr-[5px] ">

              </div>
            </div>
            {{ product.sku }}
          </div>


          <div class="px-[10PX] mt-[15PX]">
            <div class="w-[100%] py-[10PX] px-[20PX] bg-[#FD4442] rounded-[8PX] ">
              <div class="flex flex-wrap">
                <div class="w-[16PX] h-[16PX] bg mr-[10PX]"
                     style="background-image: url(https://img.alicdn.com/imgextra/i4/801089336/O1CN01S5EN2A2IpwkNHMsq7_!!801089336.png)"></div>
                <div class="text-[14PX] text-[#fff] w-[90%]">
                  {{ product.titleExternal }}
                </div>

              </div>
              <div class="flex flex-wrap mt-[10PX]">

                <div class="text-[rgba(255,255,255,0.8)] text-[12PX]">
                  {{ product.subtitle }}
                </div>

              </div>

            </div>

          </div>


          <div class="px-[10PX] mt-[15PX]" v-if="product.thaliFlag == 1">
            <div> {{ language.model }}：</div>
            <div class="mt-[15PX] flex flex-wrap">
              <div class="rounded-[8px] px-[10PX] py-[5PX] mr-[15PX] bg-[#FFF6F6] cursor-pointer"
                   v-for="(item,index) in product.thalis || []"
                   :key="index"
                   :class="`${ index == activeModel ? 'text-[#FF0C06] ' : 'text-[#333333]' }`"
                   :style="`border:solid 1px rgba(255,12,6,${ index == activeModel  ? 1 : 0 })`"
                   @click="activeModel = index"
              >
                {{ item.nameForeign }}
              </div>
            </div>
          </div>


          <div class="mt-[15PX] px-[10PX]"
               v-for="(item,index) in productInfo.newSpec[activeModel].productList || []"
               :key="index"
          >

            <div class="h-[36PX] flex items-center bg-[#F5F5F5] rounded-[8PX] pl-[10PX]">
              {{ index + 1 }}{{ language.per }} {{ language.selected }}（<span
              class="text-[#FF0C06]">{{
                item.sku.filter(item => item.selected).length
              }}</span>/{{ item.sku.length }}）
            </div>


            <div class="px-[10PX]">
              <div class="sku mt-[20PX]"
                   v-for="(item,index) in item.sku || []"
                   :key="index"
              >
                <div>{{ item.nameForeign }}</div>

                  <div class="list  flex mt-[15PX] flex-wrap">
                    <div
                      v-for="(it,idx) in item.list"
                      :key="idx"
                      @click="handleBtnClick({type:'sku',index,idx,item,it})"
                      class="mb-[15PX]"
                    >
                      <div
                        v-if="it.url"
                        class="w-[146PX] h-[180PX] px-[5PX] py-[5PX] rounded-[8PX] mr-[18PX] transition"

                        :class="`${idx+1 == item.selected ? 'bg-[#FD4442]' : 'bg-[#F5F5F5]' }`"
                      >

                        <div class="w-[100%] h-[136PX] rounded-[8PX] bg-[#fff] bg"
                             :style="`background-image:url(${ it.url });  background-size: contain;`"
                        >

                        </div>

                        <div class="mt-[12PX] flex-center"
                             :class="`${ idx+1 == item.selected ?  'text-[#fff]' : '' }`">
                          {{ it.nameForeign }}
                        </div>


                      </div>

                      <div
                        v-else
                        class=" px-[5PX] py-[5PX] rounded-[8PX] mr-[18PX] transition"

                        :class="`${idx+1 == item.selected ? 'bg-[#FD4442]' : 'bg-[#F5F5F5]' }`"
                      >

                        <div class="flex-center"
                             :class="`${ idx+1 == item.selected ?  'text-[#fff]' : '' }`">
                          {{ it.nameForeign }}
                        </div>


                      </div>

                    </div>

                  </div>


              </div>

              <div class="sku mt-[20PX]" v-if="product.thaliFlag != 1">
                <div>{{ language.number }}</div>

                <div class="mt-[15PX]">
                  <el-input-number v-model="form.number" :min="1"/>
                </div>
              </div>
            </div>

          </div>


        </div>


        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="px-[10PX] mt-[30PX]" v-if="!isNaN(computePrice.discountPrice) ">
          <div>
            {{ language.priceDetail }}
          </div>

          <div>

            <div class="flex justify-between items-end mt-[10PX]">
              <div> {{ language.originPrice }}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX]">{{ computePrice?.price }}</div>
              </div>
            </div>

            <!-- 偏远地区邮费与运费二选一 -->
            <div class="flex justify-between items-end mt-[10PX]" v-if="product.shippingFee">
              <div>{{ language.shippingFee }}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX]">{{ product.shippingFee }}</div>
              </div>
            </div>


            <!-- <div class="flex justify-between items-end mt-[10PX]" v-if="computeRemotePrice">
              <div>{{ language.remoteFee }}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX]">{{
                    computePrice.remotePostage || 0
                  }}
                </div>
              </div>
            </div> -->

            <div class="flex justify-between items-end mt-[10PX]"
                 v-if="product.commission"
            >
              <div>{{ language.commission }}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX]">{{ product.commission }}</div>
              </div>
            </div>


            <div class="flex justify-between items-end mt-[10PX]" >
              <div class="text-[#FF0C06] flex items-center">
                <div class="w-[14PX] h-[14PX] bg mr-[5PX]"
                     style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN01QBQJYv2IpwkNb8Rk2_!!801089336.png)"></div>
                {{ language.discount }}
              </div>
              <div class="flex items-end">
                <div class="mr-[5PX] text-[#FF0C06]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX] text-[#FF0C06]">
                  {{ computePrice?.lessPrice }}
                </div>
              </div>
            </div>

            <div class="flex justify-between items-end mt-[10PX]" v-if="isPickup">
              <div class="text-[#FF0C06] flex items-center">
                <div class="w-[14PX] h-[14PX] bg mr-[5PX]"
                     style="background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN014hOMDI2IpwkNwybqk_!!801089336.png)"></div>
                {{ language.couponDeduction }}
              </div>
              <div class="flex items-end">
                <div class="mr-[5PX] text-[#FF0C06]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX] text-[#FF0C06]">
                  {{ product.couponAmount || 0 }}
                </div>
              </div>
            </div>

            <div class="flex justify-between items-end mt-[10PX]">
              <div>{{ language.total1 }}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[20PX] mb-[-5PX]">{{ computePrice?.discountPrice }}</div>
              </div>
            </div>
          </div>

        </div>


        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="px-[10PX] mt-[30PX]" v-if="!isNaN(computePrice.discountPrice) ">
          <div class="flex">
            <div class="text-[#FF0C06]">*</div>
            {{ language.logisticsMethod }}
          </div>

          <div class="mt-[15PX] flex items-center  flex-wrap overauto w-[100%]">

            <div v-for="(item,index) in logisticsList" :key="index"
                 @click="handleBtnClick({ type:'logistics',index })"
            >
              <div class="w-[190PX] h-[72PX] bg mb-[10PX] mr-[10PX] transition"
                   :style="`background-image:url(${ index == form.activeLogistics ? 'https://img.alicdn.com/imgextra/i1/801089336/O1CN01D42yhk2IpwkNddK1S_!!801089336.png' : 'https://img.alicdn.com/imgextra/i3/801089336/O1CN01JcP79p2IpwkO5pPNf_!!801089336.png' });background-size:contain;`"

              >

                <div class="pl-[40PX] pt-[15PX] flex items-center">
                  <div class="w-[18PX] h-[18PX] bg mr-[5PX]"
                       :style="`background-image:url(${ item.logo })`"></div>
                  <div class="text-[16PX]">
                    {{ item.methodName }}
                  </div>
                </div>

                <div class="mt-[10px] text-[#999999] pl-[40PX]">
                  {{ item.title }}
                </div>


              </div>
            </div>

          </div>


          <div
            v-if="instruction.id"
            class="mt-[15PX] bg-[#FFF8EE] px-[20PX] py-[20PX] rounded-[8PX] text-[#8D5B0E] flex items-start"
            style="border: solid 1px rgba(141,91,14,0.2)">
            <div class="w-[15PX] h-[15PX] bg mr-[10PX]"
                 style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN01FXSiiT2IpwkHYqnkr_!!801089336.png);flex-shrink: 0;"></div>

            {{ instruction.stateInstructions }}


          </div>

        </div>


        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="px-[10PX] mt-[30PX]">
          <div class="flex">
            <div class="text-[#FF0C06]">*</div>
            {{ language.payMethod }}
          </div>

          <div class="mt-[15PX] flex items-center">
            <div class="w-[16PX] h-[16PX] bg mr-[5PX]"
                 style="background-image: url(https://img.alicdn.com/imgextra/i4/801089336/O1CN01SdoNZU2IpwkN2ooAs_!!801089336.png)"></div>
            {{ language.arrivedPay }}
          </div>

        </div>

        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>


        <div class="px-[10PX] mt-[30PX]" v-if="!isNaN(computePrice.discountPrice) ">
          <div class="flex">
            {{ language.sendMethod }}
          </div>


          <div class="mt-[15px] templateForm ">
            <el-form :model="form" :rules="rules" ref="formRef">

              <el-row :gutter="24">
                <el-col :xs="item.xs"
                        :xl="item.xl"
                        :lg="item.xl"
                        v-for="(item,index) in inputConfig"
                        :key="index"

                >

                  <el-form-item :prop="item.code"
                                v-if="((item.directly && logisticsList[form.activeLogistics]?.directlyStatus == 0) || !item.directly) ? true : false "
                  >

                    <el-input v-model="form[item.code]"
                              :placeholder="item.name"
                              :min="0"
                              v-if="!item.type || item.type == 'text'"
                              :disabled="(item.code == 'detailAddress' ? (logisticsList[form.activeLogistics]?.directlyStatus == 0 ? true  :false)  : false) || item.disabled"
                    />

                    <el-select v-model="form[item.code]"
                               :placeholder="item.name"
                               v-if="item.type == 'select'"
                               @change="onChange(item.code)"
                    >

                      <el-option v-for="(it,idx) in item.list" :key="idx" :value="it[item.value]"
                                 :label="it[item.label]"/>

                    </el-select>

                    <el-input
                      :placeholder="item.name" v-model="form[item.code]"
                      v-if="item.type == 'textarea'"
                      type="textarea"
                      :rows="5"
                      resize="none"
                    />

                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </div>


        </div>


        <div class="px-[10PX] mt-[30PX] pb-[60PX]">
          <Policy :policy-list="policyListReal"/>
          <!--          <el-collapse v-model="activeNames" @change="handleChange"-->
          <!--                       v-if="policyList && policyList.length>0">-->
          <!--            <el-collapse-item :title="item.title" :name="item.id" v-for="(item,index) in policyList"-->
          <!--                              :key="index">-->
          <!--              <div v-html="item.detail"></div>-->
          <!--            </el-collapse-item>-->

          <!--          </el-collapse>-->


        </div>


        <div class="fixed left-[0] bottom-[0] w-[100vw] flex-center" style="z-index: 3;" v-if="!isNaN(computePrice.discountPrice) ">
          <div class="w-[640PX] h-[50PX] flex-center bg-[#FF0C06] text-[#FFF] mt-[15PX]  "
               @click="handleBtnClick({type:'submit'})">{{     (computeIsAllFill ? language.submit : language.buyNow)}}
          </div>
        </div>
        <div class="fixed left-[0] bottom-[0] w-[100vw] flex-center" style="z-index: 3;" v-else>
          <div class="w-[640PX] h-[50PX] flex-center bg-[#ccc] text-[#FFF] mt-[15PX]  "
               >{{ computeIsAllFill ? language.undisabled : language.undisabled }}
          </div>
        </div>

      </div>
    </div>
    <SuccessPage v-if="showSuccess" @update:showSuccess="updateShowSuccess" :orderInfo="orderInfo"
                 :product="product"/>
  </div>

</template>
<script lang="ts" setup>

import {useMessage} from "@/hooks/web/useMessage";
import {getLanguage} from "@/utils/langue";
import {deepCopy} from "@/utils";
import SuccessPage from "@/views/Product/template/components/success.vue";
import OrderPage from "@/views/Product/template/components/order.vue";
import Evaluation from "@/views/Product/template/components/evaluation.vue";
import SwiperBuyInfo from "@/views/Product/template/components/swiperBuyInfo.vue";
import Recommend from "./components/Recommend.vue";

const message = useMessage();

const props = defineProps({
  recommendList: {
    type: Array,
    required: false,
    default: () => []
  },
  rollList: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  commentList: {
    type: Array,
    required: false,
    default: () => []
  },
  commentAvgScore: {
    type: Number,
    required: false,
    default: 0
  },

  orderInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  showSuccess: {
    type: Boolean,
    required: false,
    default: () => false
  },
  showOrder: {
    type: Boolean,
    required: false,
    default: () => false
  },
  product: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  areaInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  skuInfo: {
    type: Array,
    required: false,
    default: () => []
  },
  hasProvince: {
    type: Boolean,
    default: true,
  },
  //原商品列表sku
  originalSku: {
    type: Array,
    required: false,
    default: () => []
  },
  provinceList: {
    type: Array,
    required: false,
    default: () => []
  },
  logisticsList: {
    type: Array,
    required: false,
    default: () => []
  },
  storeList: {
    type: Array,
    required: false,
    default: () => []
  },
  globalConfig: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  policyList: {
    type: Array,
    required: false,
    default: () => []
  },
  time: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  remoteList: {
    type: Array,
    required: false,
    default: () => []
  },
  instruction: {
    type: Object,
    required: false,
    default: () => {
    }
  }
});

const formRef = ref(null)

const emit = defineEmits(['confirm', 'execute']);

const isPickup = ref(false)

const skuList = ref([])

const language = ref(getLanguage(props.product.language));

const activeModel = ref(0);

const productInfo = ref({})


const config = ref([
  {
    name: language.value.freeFee,
  },
  {
    name: language.value.arrivedPay,
  },
  {
    name: language.value.day15s,
  },
  {
    name: language.value.guarantee,
  }
])


const activeNames = ref("1");


const policyListReal = computed(() => {
  return props.policyList.filter(item => {
    return item.type == 3
  })
})


const computePrice = computed(() => {
  //获取sku列表
  //查看是否全部选中
  let isAllSelected = isAllPropertySelected().isAllSelected
  const shippingFeeValue = Number(
    computeRemotePrice.value ? props.product.remotePostage :
      props.product.thaliFlag
        ? props.product.thalis[activeModel.value]?.shippingFee || 0
        : props.product.shippingFee || 0
  );
  if (isAllSelected) {

    let selectArr = isAllPropertySelected().selectedItem;
    let totalOriginalPrice = 0;
    let totalDiscountPrice = 0;

    console.log(selectArr)

    if (props.product.thaliFlag != 1) {
      selectArr.forEach(item => {
        console.log(item, "======")
        totalOriginalPrice += item?.price * parseInt(form.value.number);
        totalDiscountPrice += item?.discountedPrice * parseInt(form.value.number);
      })
    } else {
      totalOriginalPrice = Number(props.product.thalis[activeModel.value].originalPrice);
      totalDiscountPrice = Number(props.product.thalis[activeModel.value].discountedPrice);
    }
    if (!totalDiscountPrice) totalDiscountPrice = totalOriginalPrice

    if (props.product.couponAmount && isPickup.value) {
      totalDiscountPrice -= (props.product.couponAmount || 0)
    }

    return {
      price: totalOriginalPrice.toFixed(2),//原价
      discountPrice:
        (totalDiscountPrice + (shippingFeeValue || 0) + (props.product.commission || 0)).toFixed(2),//折扣价
      remotePostage: (computeRemotePrice.value ? (props.product.remotePostage || 0) : 0).toFixed(2),//远程费
      // shippingFee:(props.product.shippingFee || 0).toFixed(2),//运费
      shippingFee: shippingFeeValue.toFixed(2),//套餐的运费优先
      commission: (props.product.commission || 0).toFixed(2),//佣金
      lessPrice: (totalOriginalPrice - totalDiscountPrice).toFixed(2),//优惠价格
    }

  } else {
    //如果是套餐需要根据选中的套餐价格变化

    if (props.product.thaliFlag) {
      const price = props.product.thalis[activeModel.value].discountedPrice ? props.product.thalis[activeModel.value].discountedPrice : Number(props.product.combo[activeModel.value].originalPrice).toFixed(2)//原价
      return {
        price: Number(props.product.thalis[activeModel.value].originalPrice).toFixed(2),//原价
        // discountPrice:(Number( props.product.thalis[activeModel.value].discountedPrice) - (isPickup.value ? (props.product.couponAmount || 0) : 0) ).toFixed(2),//折扣价

        discountedPrice: Number(price + (computeRemotePrice.value ? (props.product.remotePostage || 0) : 0) + (shippingFeeValue || 0) + (props.product.commission || 0)).toFixed(2),
        remotePostage: Number(computeRemotePrice.value ? (props.product.remotePostage || 0) : 0).toFixed(2),//远程费
        shippingFee: shippingFeeValue.toFixed(2),//运费
        commission: Number(props.product.commission || 0).toFixed(2),//佣金
        lessPrice: Number(props.product.originalPrice - (props.product.discountedPrice || 0)).toFixed(2),//优惠价格
      }
    } else {
      const price = props.product.discountedPrice ? Number(props.product.discountedPrice).toFixed(2) : Number(props.product.originalPrice).toFixed(2)//原价
      return {
        price: price,//原价
        // discountPrice:(props.product.discountedPrice - (isPickup.value ? (props.product.couponAmount || 0) : 0) ).toFixed(2),//折扣价
        discountedPrice: Number(price + (computeRemotePrice.value ? (props.product.remotePostage || 0) : 0) + (shippingFeeValue || 0) + (props.product.commission || 0)).toFixed(2),
        remotePostage: Number(computeRemotePrice.value ? (props.product.remotePostage || 0) : 0).toFixed(2),//远程费
        shippingFee: shippingFeeValue.toFixed(2),//运费
        commission: Number(props.product.commission || 0).toFixed(2),//佣金
        lessPrice: Number(props.product.originalPrice - (props.product.discountedPrice || 0)).toFixed(2),//优惠价格
      }
    }


  }
})


const computeInput = computed(() => {
  let arr = [];
  //邮箱
  if (props.product.emailShow) {
    arr.push({
      name: language.value.email,
      code: "email",
      xs: 24,
      xl: 24,
      required: !!props.product.emailFlag,
      show: true,
    })
  }

  //邮编
  if (props.product.zipCodeShow) {
    arr.push({
      name: language.value.postalCode,
      code: "postalCode",
      xs: 24,
      xl: 24,
      required: !!props.product.zipCodeFlag,
      show: true,
    })
  }

  //建筑物
  if (props.product.houseNumberShow) {
    arr.push({
      name: language.value.houseNumber,
      code: "houseNumber",
      xs: 24,
      xl: 24,
      required: !!props.product.houseNumberFlag,
      show: true,
    })
  }

  //Whatsapp
  if (props.product.whatsappShow) {
    arr.push({
      name: "whatsapp",
      code: "whatsapp",
      xs: 24,
      xl: 24,
      required: !!props.product.whatsappFlag,
      show: true,
    })
  }

  //Line
  if (props.product.lineShow) {
    arr.push({
      name: "line",
      code: "line",
      xs: 24,
      xl: 24,
      required: !!props.product.lineFlag,
      show: true,
    })
  }
  return arr
})

const inputConfig = ref([
  {
    name: language.value.name,
    code: "customerName",
    xs: 24,
    xl: 24,
    required: true,
    show: true,
  },
  {
    name: language.value.phone,
    code: "customerPhone",
    xs: 24,
    xl: 24,
    required: true,
    show: true,
  },
  {
    name: language.value.area,
    code: "areaName",
    xs: 24,
    xl: 8,
    required: true,
    disabled: true
  },
  {
    name: language.value.areaName,
    code: "cityName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show: props.hasProvince,
  },
  {
    name: language.value.cityName,
    code: "regionName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show: props.hasProvince,
  },
  {
    name: language.value.selectStore,
    code: "addressId",
    type: "select",
    label: "name",
    value: "id",
    xs: 24,
    xl: 24,
    required: false,
    directly: true,
    show: true,
  },
  {
    name: language.value.address,
    code: "detailAddress",
    xs: 24,
    xl: 24,
    required: true,
    show: true,
  },
  ...computeInput.value,
  {
    name: language.value.message,
    code: "message",
    type: "textarea",
    xs: 24,
    xl: 24,
    required: false,
    show: true,
  }
]);

/**
 * 计算rules
 * */
const rules = computed(() => {

  let obj = {}
  inputConfig.value.forEach(item => {
    if (item.required) {
      obj[item.code] = [{
        required: true,
        message: `${language.value.please}${item.type == 'select' ? language.value.select : language.value.input}${item.name}`,
        trigger: `${item.type == 'select' ? 'change' : 'blur'}`
      }]
    }

  })

  return obj
})

/**计算是否需要偏远地区费用*/
const computeRemotePrice = computed(() => {
  let list = props.remoteList;
  let area = form.value.cityName;
  let it = list.find(at => {
    return at.city == area
  })
  return !!it

})


const computeSku = (pindex, index) => {
  try {
    let skuInfo = props.product.thalis[pindex].thaliDetailList[index].specs || [];


    let list = deepCopy(skuInfo)
    if (list.length > 0) {
      let arr = []

      let sizeArr = (list[0].name || '').split(/§/gi)

      let sizeFoeignArr = (list[0].nameForeign || '').split(/§/gi)
      sizeArr.forEach((item, index) => {
        //找到 不重复的 属性
        let obj = {
          name: item,
          nameForeign: sizeFoeignArr[index],
          list: []
        }
        list.forEach((it) => {
          let propertyArr = (it?.propertyValue || '').split(/§/gi)
          let propertyValueForeignArr = (it?.propertyValueForeign || '').split(/§/gi)
          let imgArr = (it?.picture || '').split(/,/gi)
          let isIn = obj.list.find((at) => {
            return at.nameForeign == propertyValueForeignArr[index]
          })
          if (!isIn) {
            obj.list.push({
              name: propertyArr[index],
              nameForeign: propertyValueForeignArr[index],
              url: (imgArr && imgArr.length > 0 && imgArr[index]) || ''
            })
          }
        })

        arr.push(obj)
      })
      if (arr.length == 1) {
        arr[0].selected = 1
      }

      return arr
    } else {
      return []
    }
  } catch (e) {
    console.log(e)
  }
}


let initForm = {
  number: 1,
  activeLogistics: 0
}

const form = ref({
  ...initForm
})


/**
 * 判断是否所有信息都填写了
 * */
const computeIsAllFill = computed(() => {
  let fo = form.value;
  let config = inputConfig.value;

  let isAllFill = true;
  for (let i = 0; i < config.length; i++) {
    if (config[i].required) {

      if (!fo[config[i].code]) {
        isAllFill = false;
        break;
      }

    }
  }

  return isAllFill;

})


const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const isAllPropertySelected = () => {
  let selectedItem = []
  let isAllSelected = true;

  let productList = deepCopy(productInfo.value.newSpec[activeModel.value].productList || []);

  productList.forEach((item) => {
    let skuList = item.sku || [];
    for (let i = 0; i < skuList.length; i++) {
      if (!skuList[i].selected) {
        isAllSelected = false;
        break;
      }
    }
  })


  if (isAllSelected) {
    productList.forEach((item, index) => {
      let skuList = item.sku || [];
      //拿到原来的规格
      let oldSpes = productInfo.value.thalis[activeModel.value].thaliDetailList[index].specs || [];

      console.log(oldSpes,"oldSpecs")

      if (oldSpes.length == 1) {
        //长度为1  默认选中
        selectedItem = deepCopy(oldSpes)
      } else {
        let selectedArr = [];

        skuList.forEach(it => {
          selectedArr.push(it.list[it.selected - 1])
        })

        let name = selectedArr.map(item => item.name).join('§');

        let selectedObj = oldSpes.find(at => {
          return at.propertyValue == name
        })
        if(selectedObj){
          selectedItem.push(selectedObj);
        }

      }


    })
  }

  return {
    selectedItem,
    isAllSelected
  }
}

const fn = {
  pickupCoupon() {
    if (!isPickup.value) {
      isPickup.value = true;
      message.success(language.value.reactived)
    }
  },
  async submit() {

    if(!computeIsAllFill.value){

      //跳转到锚点
      scrollTo('templateForm')
      return;
    }

    try {
      let res = await formRef.value.validate();

      let item = inputConfig.value.find(item => {
        return item.code == 'regionName'
      })

      //查看有没有v选择sku
      if (isAllPropertySelected().isAllSelected) {

        let addressItem = inputConfig.value.find(at => {
          return at.code == "addressId"
        })

        let address = null;
        if (addressItem) {
          let lis = addressItem.list;

          if (form.value.addressId) {
            address = lis.find(at => {
              return at.id == form.value.addressId
            })?.name
          }
        }


        emit('execute', {
          type: 'confirm',
          form: form.value,
          address: address,
          skuList: skuList.value,
          priceInfo: computePrice.value,
          isPickup: isPickup.value,
          selectedProperty: isAllPropertySelected().selectedItem,
          thaliId: productInfo.value.thaliFlag == 1 ? productInfo.value.thalis[activeModel.value]?.id : '',
          thaliName: productInfo.value.thaliFlag == 1 ? productInfo.value.thalis[activeModel.value]?.nameForeign : '',
          thaliPrice: productInfo.value.thaliFlag == 1 && productInfo.value.thalis[activeModel.value]?.discountedPrice ? productInfo.value.thalis[activeModel.value]?.discountedPrice : productInfo.value.thalis[activeModel.value]?.originalPrice,
          success() {
            if (props.globalConfig.orderDelectSteat == 1) {
              form.value = {
                ...initForm
              }
            }

          }
          //其他 sku等信息
        })
      } else {
        message.error(language.value.noSku);
      }


    } catch (e) {
      console.log(e)
      for (let i in e) {
        message.error(e[i][0].message);
        return
      }
    }
  },
  logistics({index}) {
    if (index != form.value.activeLogistics) {
      form.value.activeLogistics = index;
      form.value.cityName = '';
      form.value.regionName = '';
      emit('execute', {
        type: 'logistics',
        method: props.logisticsList[form.value.activeLogistics]
      })
    }


  },
  sku({item, it, index, idx}) {
    item.selected = idx + 1;
  }
}


const scrollTo = (className) => {
  const element = document.querySelector(`.${className}`)
  if (element) {
    // 平滑滚动到指定元素
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })

    // 如果需要偏移量（如固定头部）
    // window.scrollTo({
    //   top: element.offsetTop - 80,
    //   behavior: 'smooth'
    // })
  }
}

const updateShowSuccess = (val) => {
  //关闭成功页面
  emit('execute', {
    type: 'closeSuccess',
  })
}

const updateShowOrder = () => {
  //关闭成功页面
  emit('execute', {
    type: 'closeOrder',
  })
}


const onChange = code => {
  if (code == 'cityName') {

    form.value.regionName = ''
    //生成
    let item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })

    //获取市
    let it = props.provinceList.find(at => {
      return at.name == form.value[code];
    })
    if (item) {
      item.list = it.list || [];
    }
    // item = inputConfig.value.find(at => {
    //   return at.code == 'regionName'
    // })
    //
    // item.list = []

    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    if (item) {
      item.list = [];
    }


  } else if (code == 'regionName') {


    let item1 = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })

    let it = item1.list.find(at => {
      return at.name == form.value.cityName
    })


    let item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    if (item) {
      item.list = [];
    }

  } else if (code == 'addressId') {
    let it = props.storeList.find(at => {
      return at.id == form.value[code]
    })

    form.value.detailAddress = it.detailedAddress
  }
}


watch(() => props.provinceList, () => {
  let item = inputConfig.value.find(at => {
    return at.code == 'cityName'
  })
  item.list = props.provinceList
}, {
  deep: true,
  immediate: true
})

const initProductInfo = () => {
  let product = deepCopy(props.product);
  product.newSpec = [];
  product.thalis.forEach((item, pindex) => {
    let obj = {
      ...item,
      productList: []
    }
    //循环商品
    item.thaliDetailList.forEach((it, idx) => {
      obj.productList.push({
        sku: computeSku(pindex, idx)
      })
    })
    product.newSpec.push(obj)
  })

  console.log(product,"ppppppppppppppppppppppp")

  productInfo.value = product
}

watch(() => [form.value.activeLogistics, form.value.regionName], () => {
  if (form.value.regionName) {
    if (props.logisticsList[form.value.activeLogistics]?.directlyStatus == 0) {
      //获取store
      emit('execute', {
        type: 'store',
        data: form.value,
        callback(storeList) {
          let item = inputConfig.value.find(at => {
            return at.code == 'addressId'
          })
          item.list = storeList.map(item => {
            return {
              id: item.id,
              name: item.storeName,
              address: item.detailedAddress
            }
          })
        }
      })
    }

  }
}, {
  deep: true,
  immediate: true
})

watch(() => props.skuInfo, () => {
  skuList.value = props.skuInfo;
}, {
  deep: true,
  immediate: true
})

watch(() => props.product, () => {
  initProductInfo();
}, {
  deep: true,
  immediate: true
})

onMounted(() => {
  form.value.areaName = props.product.stateBigName
})
</script>
<style>
</style>
<style scoped lang="less">
@import "@/common";

.index {
  .content {
    width: 640PX;
    height: 100%;

    .top-title {
      font-size: 14PX !important;

      .bar {
        width: 4PX;
      }
    }

    .subTitle {
      font-size: 14PX !important;
    }

    .swiper {
      width: 100%;
      height: 640PX;

      .swiper-item {
        width: 100%;
        height: 640PX;
      }

      .benefit {
        width: 100%;
        height: 64PX;

        .qianggou-num {
          padding: 5PX 12PX;
        }
      }

      .cycle {
        width: 27PX;
        height: 27PX;
        border-radius: 5PX;
        background: #FD4442;
      }
    }


    .price {
      font-size: 28PX;
      margin-bottom: -5PX;
    }

    .coupon {
      width: 100%;
      height: 45PX;
      padding-left: 60PX;
    }


    .icons {
      width: 14PX;
      height: 14PX;
    }
  }

  .ft12 {
    font-size: 12PX !important;
  }
}

@media screen and (max-width: 640PX) {
  .index {
    .content {
      width: 100%;

      .swiper {
        width: 100vw;
        height: 100vw;

        .swiper-item {
          width: 100vw;
          height: 100vw;
        }
      }
    }

    .ft12 {
      .font(18);
    }

  }
}

:deep(.el-carousel) {
  width: 100%;
  height: 100%;

  .el-carousel__container {
    width: 100%;
    height: 100%;
  }
}

:deep(.el-input-number) {
  width: 135PX;
  height: 30PX;

  .el-input-number__decrease, .el-input-number__increase {
    width: 28PX;
    height: 28PX;
    border-radius: 0PX;
  }

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
  }

  .el-icon {
    font-size: 14PX;
  }

}

:deep(.el-input) {
  height: 30PX;

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 5PX;
  }


}

:deep(.el-textarea ) {
  height: 60PX !important;

  .el-textarea__inner {
    height: 60PX !important;
    font-size: 10PX;
  }

}


:deep(.el-select) {
  height: 30PX !important;

  .el-select__selected-item, .el-input__inner, .el-select__wrapper {
    height: 30PX !important;


  }

  .el-select__placeholder {
    display: flex !important;
    align-content: center;
    align-items: center;
  }

}

:deep(.el-form-item) {
  margin-bottom: 0PX;
  margin-top: 15PX;
}
</style>
